<?php
namespace app\index\home;
use app\index\home\Base;
use think\Db;
use think\Request;
class Wxoauth extends Base
{
    protected function initialize()
    {
       parent::initialize();
       
    }

    function index(){
        echo config('APPID');
    }
    // 通过code获取用户openid
    function getUserinfoBycode(){
        $post_data = file_get_contents('php://input');
        // var_dump($post_data);exit;
        $post_data=json_decode($post_data,true);
        if(!$post_data){
            errMsg('defined');
        }
        $code = $post_data['code'];
        $codeinfo=$this->getOpenIdByCode($code);//获取用户openid

		$openid=$codeinfo['openid'];

        $data = array('openid'=>$openid,'session_key'=>$codeinfo['session_key']);
		okMsg($data);
    }

    // 通过授权后通过openid保存用户基本信息，获取用户userid
    function saveUserinfo(){
        $post_data = file_get_contents('php://input');
        if(!$post_data){
            errMsg('defined');
        }
        $post_data = json_decode($post_data,true);
        
        $openid = $post_data['openid'];
        $user_id = Db::name('user')->where('openid',$openid)->value('id');
        if(!$user_id){
            $ip = $this->getHostIp();
            if(!$ip){
                $ip = '';
            }
            $in_data = array(
                'openid'=>$openid,
                'nickname'=>$post_data['nickName'],
                'headimg'=>$post_data['avatarUrl'],
                'gender'=>$post_data['gender'],
                'ctime'=>time(),
                'first_login_time'=>time(),
                'last_login_time'=>time(),
                'ip'=>$ip
            );
            if(isset($post_data['pid'])){
                $in_data['parent_id'] = $post_data['pid'];
            }
            $rs = Db::name('user')->insert($in_data);
            if($rs){
                $user_id = Db::name('user')->getLastSql();
            }
        }
        else{
            $up_data = array(
                'nickname'=>$post_data['nickName'],
                'headimg'=>$post_data['avatarUrl'],
                'gender'=>$post_data['gender'],
                'last_login_time'=>time(),
                'ip'=>$ip
            );
            $rs = Db::name('user')->where('id',$user_id)->update($up_data);
        }

        // $data['getCokey'] = $this->getCokey('wxcode_'.$user_id);
        $data['openid'] = $openid;
        okMsg($data);
        // okMsg(array('user_id'=>$this->think_encrypt($user_id,$openid)));
    }


    function getUserId(){
        $key=$_SERVER['HTTP_COKEY'];
		$decrykey=$this->encryptDecrypt('23dsdkk66lbd3wq123dsaaooasr321',$key,1);
		
		$arr=explode('_',$decrykey);
		$uid=intval($arr[1]);
        $data['uid'] = $uid;
        okMsg($data);
        // return $uid;
    }

    // 获取用户基本信息，缓存到前端展示
    function getBasicInfo(){
        // $key=$_SERVER['HTTP_COKEY'];
		// $decrykey=$this->encryptDecrypt('23dsdkk66lbd3wq123dsaaooasr321',$key,1);
		
		// $arr=explode('_',$decrykey);
		// $uid=intval($arr[1]);

        $post_data = file_get_contents('php://input');
        if(!$post_data){
            errMsg('defined');
        }
        $post_data = json_decode($post_data,true);
        
        $openid = $post_data['openid'];
        if(!$openid){
            noLogin();
        }
        // if(!$uid){
        //     noLogin();
        // }
        
        $list = Db::name('user')->where('openid',$openid)->field('id,openid,nickname,headimg,phone,department,is_partner,level,email,gender,jifen,province,city')->find();
        if(!$list){
            noLogin();
        }
        else{
            // $quan_num = Db::name('user_quan')->where(array('uid'=>$list['id'],'status'=>0))->count('id');
            $time = time();
            $qwhere[] = ['a.uid','eq',$list['id']];
            $qwhere[] = ['a.status','eq',0];
            $qwhere[] = ['b.use_bg_time','lt',$time];
            $qwhere[] = ['b.use_end_time','gt',$time];
            $quan_num = Db::name('user_quan')->alias('a')->join('product_quan b','a.quan_id=b.id','left')->where($qwhere)->count('a.id');
            $order_list = Db::name('orders')->where('uid',$list['id'])->field('pay_status,refund_status,is_send,is_que,is_refund')->select();
            $notpay_order_num = 0;
            $notsend_order_num = 0;
            $notget_order_num = 0;
            $refund_order_num = 0;
            $is_finish_order_num = 0;

            foreach($order_list as $key=>$value){
                if($value['is_refund']==1){
                    $refund_order_num+=1;
                }
                elseif($value['pay_status']==0){
                    $notpay_order_num+=1;
                }
                elseif($value['pay_status']==1&&$value['is_send']==0){
                    $notsend_order_num+=1;
                }
                elseif($value['pay_status']==1&&$value['is_send']==1&&$value['is_que']==0){
                    $notget_order_num+=1;
                }
                else{
                    $is_finish_order_num+=1;
                }
            }
            $list['quan_num'] = $quan_num;
            $list['notpay_order_num'] = $notpay_order_num;
            $list['notsend_order_num'] = $notsend_order_num;
            $list['notget_order_num'] = $notget_order_num;
            $list['refund_order_num'] = $refund_order_num;
            $list['is_finish_order_num'] = $is_finish_order_num;

            
            $up_data = array(
                'last_login_time'=>time(),
                'ip'=>$this->getHostIp(),
            );
            Db::name('user')->where('openid',$openid)->update($up_data);
            okMsg($list);
        }

    }

    //根据授权code获取openid和sessionkey
	function getOpenIdByCode($code){
		$appid=config('APPID');
        $secret=config('APPSECRET');
		$url="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
		//$data=file_get_contents($url);
		
		$curl=curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_HEADER,0);//默认已经不输出头部
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl,CURLOPT_POST,0);//默认已经是GET方式

        $data = curl_exec($curl);//修复
		
		$result=json_decode($data,true);
		$result['appid']=config('appid');
		return $result;
	}

    function test(){
        $uid = 123;
        $key = 'hello';
        $rs = $this->think_encrypt($uid,$key);
        echo "加密后：".$rs;

        $res = $this->think_decrypt($rs,$key);
        echo "<br />解密后：".$res;
    }
    function getCokey($str){
		return $this->encryptDecrypt('23dsdkk66lbd3wq123dsaaooasr321',$str,0);
	}

    function encryptDecrypt($key,$string,$decrypt){
		
		if($decrypt){
		$decrypted=rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256,md5($key),base64_decode($string),MCRYPT_MODE_CBC,md5(md5($key))),"12");
		return $decrypted;
		}else{
			$encrypted=base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256,md5($key),$string,MCRYPT_MODE_CBC,md5(md5($key))));
			return $encrypted;
		}
	}

    //对uid进行加密
    function think_encrypt($data, $key = '', $expire = 0) {
        $key  = md5(empty($key) ? Env::get('CRYPT_KEY') : "");
        $data = base64_encode($data);
        $x    = 0;
        $len  = strlen($data);
        $l    = strlen($key);
        $char = '';
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) $x = 0;
            $char .= substr($key, $x, 1);
            $x++;
        }
        $str = sprintf('%010d', $expire ? $expire + time():0);
        for ($i = 0; $i < $len; $i++) {
            $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
        }
        return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
    }
 
    //对uid解密
    function think_decrypt($data, $key = ''){
        $key    = $key  = md5(empty($key) ? Env::get('CRYPT_KEY') : "");
        $data   = str_replace(array('-','_'),array('+','/'),$data);
        $mod4   = strlen($data) % 4;
        if ($mod4) {
        $data .= substr('====', $mod4);
        }
        $data   = base64_decode($data);
        $expire = substr($data,0,10);
        $data   = substr($data,10);
        if($expire > 0 && $expire < time()) {
            return '';
        }
        $x      = 0;
        $len    = strlen($data);
        $l      = strlen($key);
        $char   = $str = '';
        for ($i = 0; $i < $len; $i++) {
            if ($x == $l) $x = 0;
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++) {
            if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            }else{
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return base64_decode($str);
    }

    public function getHostIp()
    {
        //tp内置函数获取客户端ip
        $ip = request()->ip();
        return $ip;
    }

    // 获取用户地理位置信息
    public function getUserLocation(){
        $openid = input('openid/s');
        $province = input('province/s');
        $city = input('city/s');
        $district = input('district/s');

        $user_check = Db::name('user')->where('openid',$openid)->value('province');
        if(!$user_check){
            $up_data = array('province'=>$province,'city'=>$city,'district'=>$district);
            $rs = Db::name('user')->where('openid',$openid)->update($up_data);
            if($rs){
                okMsg('更新成功');
            }
            else{
                errMsg('更新失败，请重试');
            }
        }
        else{
            errMsg('用户位置信息已存在，无需更新');
        }
    }
}
?>